//
//  BKStatusViewModel.swift
//  微博
//
//  Created by mac on 16/8/12.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit

class BKStatusViewModel: NSObject {

    var status:BKStatus?
    
    var retweetCountContent: String?
    var commentCountContent:String?
    var unlikeCountContent:String?
    
    var sourceContent:String?
    
    //转发微博的内容
    var retweetContent:String?
    
    //通过重载构造函数初始化当前对象
    init(status:BKStatus) {
        super.init()
        self.status = status
        retweetCountContent = handleCount(status.reposts_count, defaultTitle: "转发")
        commentCountContent = handleCount(status.reposts_count, defaultTitle: "评论")
        unlikeCountContent = handleCount(status.reposts_count, defaultTitle: "赞")
        
        handleSource(status.source ?? "")
        handleRetweetContent(status)
    }
    //处理来源数据
    private func handleSource(source: String) {
        //  判断字符串中是否包含这样关键字符串
        if source.containsString("\">") && source.containsString("</") {
            //  开始光标位置
            let startIndex = source.rangeOfString("\">")!.endIndex
            //  结束光标位置
            let endIndex = source.rangeOfString("</")!.startIndex
            
            //  获取指定范围的字符串
            let result = source.substringWithRange(startIndex..<endIndex)
            //  设置给来源数据
            sourceContent = "来自: " + result
        }
        
        
        
    }
    
    //转发微博内容的拼接
    private func handleRetweetContent(status:BKStatus){
    
        if status.retweeted_status != nil {
        
            guard let text = status.retweeted_status?.text,let name = status.retweeted_status?.user?.screen_name else {
            
                return
            }
            //拼接转发微博内容
            let result = "@\(name): \(text)"
            retweetContent = result
        }
    }
    
    private func handleCount(count:Int,defaultTitle:String)->String{
    
        if count > 0{
        
            if count >= 10000{
            
                let result = CGFloat(count/1000) / 10
                var resultStr = "\(result)万"
                
                if resultStr.containsString(".0"){
                
                    resultStr = resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
                }
                return resultStr
                
            }else{
            
                return "\(count)"
            }
        }else{
        
        
            return defaultTitle
        }
    }
}
